/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.ExamOrder;
import me.zhengjie.modules.system.repository.ExamOrderRepository;
import me.zhengjie.modules.system.service.ExamOrderService;
import me.zhengjie.modules.system.service.dto.ExamOrderDto;
import me.zhengjie.modules.system.service.dto.ExamOrderQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.ExamOrderMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author wangyu
* @date 2021-11-25
**/
@Service
@RequiredArgsConstructor
public class ExamOrderServiceImpl implements ExamOrderService {

    private final ExamOrderRepository examOrderRepository;
    private final ExamOrderMapper examOrderMapper;

    @Override
    public Map<String,Object> queryAll(ExamOrderQueryCriteria criteria, Pageable pageable){
        Page<ExamOrder> page = examOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(examOrderMapper::toDto));
    }

    @Override
    public List<ExamOrderDto> queryAll(ExamOrderQueryCriteria criteria){
        return examOrderMapper.toDto(examOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ExamOrderDto findById(Long orderId) {
        ExamOrder examOrder = examOrderRepository.findById(orderId).orElseGet(ExamOrder::new);
        ValidationUtil.isNull(examOrder.getOrderId(),"ExamOrder","orderId",orderId);
        return examOrderMapper.toDto(examOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ExamOrderDto create(ExamOrder resources) {
        return examOrderMapper.toDto(examOrderRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ExamOrder resources) {
        ExamOrder examOrder = examOrderRepository.findById(resources.getOrderId()).orElseGet(ExamOrder::new);
        ValidationUtil.isNull( examOrder.getOrderId(),"ExamOrder","id",resources.getOrderId());
        examOrder.copy(resources);
        examOrderRepository.save(examOrder);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long orderId : ids) {
            examOrderRepository.deleteById(orderId);
        }
    }

    @Override
    public void download(List<ExamOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ExamOrderDto examOrder : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("订单编号", examOrder.getOrderNo());
            map.put("订单时间", examOrder.getCreateTime());
            map.put("订单金额", examOrder.getOrderAmount());
            map.put("支付金额", examOrder.getPayAmount());
            map.put("优惠金额", examOrder.getDiscountAmount());
            map.put("用户微信id", examOrder.getOpenId());
            map.put("预支付流水号", examOrder.getPrePayid());
            map.put("测试id", examOrder.getAtmrId());
            map.put("支付流水号", examOrder.getPaySerialid());
            map.put("支付状态，0：未支付，1：已支付", examOrder.getPayStatus());
            map.put("订单状态", examOrder.getOrderStatus());
            map.put("是否团体免费测评0：不是，1L是", examOrder.getTeamTestid());
            map.put("更新时间", examOrder.getUpdateTime());
            map.put("是否答题，0：未答题，1：已答题", examOrder.getBeAnswer());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    @Override
    public ExamOrder findOne(String orderSn) {
        ExamOrderQueryCriteria criteria = new ExamOrderQueryCriteria();
        criteria.setOrderNo(orderSn);
        List<ExamOrder> all = examOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        if (CollectionUtils.isEmpty(all)){
            return null;
        }
        return all.get(0);
    }

    @Override
    public ExamOrder findOne(Integer resultId) {
        if(ObjectUtils.isEmpty(resultId)){
            return null;
        }
        ExamOrderQueryCriteria criteria = new ExamOrderQueryCriteria();
        criteria.setResultId(resultId);
        List<ExamOrder> all = examOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        if (CollectionUtils.isEmpty(all)){
            return null;
        }
        return all.get(0);
    }
}